package com.aceitunaproject.server.message.processor;

import java.util.logging.Logger;

import com.aceitunaproject.server.exceptions.gamerules.IllegalActionException;
import com.aceitunaproject.server.player.Player;
import com.aceitunaproject.server.unit.UnitManager;
import com.aceitunaproject.shared.message.Message;
import com.aceitunaproject.shared.message.concrete.MapAreaRefreshEvent;
import com.aceitunaproject.shared.message.concrete.MoveRequest;
import com.sun.sgs.app.AppContext;

/**
 * Handles the "Move" action request.
 * Moves the unit to the destination map tile, if the move is legal.
 * 
 * @author Federico Bergstein
 *
 */
public class MoveRequestProcessor implements MessageProcessor {

	private static Logger logger = Logger.getLogger(MoveRequestProcessor.class.getName());
	
	/**
	 * {@inheritDoc}
	 */
	@Override
		public void processMessage(Player player, Message message) {
		
		MoveRequest moveRequest = (MoveRequest)message;
		logger.fine("ordered to move unit " + moveRequest.getElementId() + " to " + moveRequest.getDestinationX() +" , " + moveRequest.getDestinationY());

		try {
			
			AppContext.getManager(UnitManager.class).moveUnit(moveRequest.getElementId(), moveRequest.getDestinationX(), moveRequest.getDestinationY());
			
			//TODO: Consider, the response message should be sent from the processor? or from the unit service?.
			
			//refreshes the user map to reflect the unit's movement.
			MapAreaRefreshEvent response = new MapAreaRefreshEvent();
			//TODO: fill response message with the appropriate map data.
			
			
			player.sendObjectMessage(response);
			
		} catch (IllegalActionException e) {
			// TODO return invalid action list to the player
			
		}

		}

}
